package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
        //String password = DigestUtils.md5DigestAsHex(param.getPassword().getBytes());
        //获取前端传过来的密码
        String password = param.getPassword();
        //调用密码认证方法
        boolean b = checkPassword(password, user.getPassword());
        if (null == user || !b) {
            log.info("[登录]失败，user:{}",param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //到这表示用户登录成功,需要将用户信息或id存入会话中
        //获取会话对象---通过请求对象
        HttpSession session = request.getSession();
        //将查到的用户Id存放在会话中
        session.setAttribute("user",user);
        log.info("[登录]成功，user:{}",user.getUsername());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().invalidate();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    //密码校验方法
    public static boolean checkPassword(String password,String dbPassword){
        if(dbPassword.startsWith("{md5}")){
            // 如果是Md5密码
            String mdPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            return mdPassword.equals(dbPassword.replace("{md5}",""));
        } else if(dbPassword.startsWith("{bcrypt}")){
            // 如果是bcrypt加密
            return BCrypt.checkpw(password,dbPassword.replace("{bcrypt}",""));//解密
        }
        // 未加密
        return password.equals(dbPassword);
    }
}
